package com.im.partchat.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.im.partchat.R;
import com.im.partchat.bean.User;
import com.im.partchat.ui.activity.SelectFriendsActivity;
import com.im.partchat.widget.GlideCircleTransform;

import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

public class SelectPersonAdapter extends BaseAdapter {

	private List<User> memsList = null;
	private Context context = null;
	private boolean showWord = true;
    private boolean showCheckBox = false;
	private UpdateChoose updateChoose;
	public interface UpdateChoose {
		void update();
	}
	public SelectPersonAdapter(List<User> memsList, Context context, UpdateChoose updateChoose) {
		this.memsList = memsList;
		this.context = context;
		this.updateChoose = updateChoose;
	}

    public boolean isShowCheckBox() {
        return showCheckBox;
    }

    public void setShowCheckBox(boolean showCheckBox) {
        this.showCheckBox = showCheckBox;
    }

    @Override
	public int getCount() {
		if (this.memsList == null) {
			return 0;
		}
		return this.memsList.size();
	}

	@Override
	public Object getItem(int position) {
		return this.memsList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(R.layout.group_member_list_item, null);
			holder.word = (TextView)convertView.findViewById(R.id.txl_word);
			holder.name = (TextView)convertView.findViewById(R.id.cylxr_txl_list_item_name);
			holder.img = (ImageView)convertView.findViewById(R.id.offline_txl_list_item_icon);
			holder.img_mark = (ImageView) convertView.findViewById(R.id.avator_mark);
            holder.checkBox = (CheckBox)convertView.findViewById(R.id.cylxr_checkbox);
            holder.clickArea = (LinearLayout)convertView.findViewById(R.id.ly_click_area);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		final User address = this.memsList.get(position);
		if (address != null) {
			holder.name.setText(address.getName());
			if (showWord) {
				String currentStr = getAlpha(address.getJp()); // 姓名首字母
				String previewStr = (position - 1) >= 0 ? getAlpha(this.memsList.get(
						position - 1).getJp()) : " ";
				if (!previewStr.equals(currentStr)) {
					holder.word.setVisibility(View.VISIBLE);
					holder.word.setText(currentStr);
				} else {
					holder.word.setVisibility(View.GONE);
				}
			} else {
				holder.word.setVisibility(View.GONE);
			}
            if (isShowCheckBox()) {
                holder.clickArea.setVisibility(View.VISIBLE);
            } else {
                holder.clickArea.setVisibility(View.GONE);
            }
			holder.checkBox.setChecked(false);
			if (SelectFriendsActivity.choosed != null) {
				for (User groupMemberBean : SelectFriendsActivity.choosed) {
					if (TextUtils.equals(groupMemberBean.getId(), address.getId())) {
						holder.checkBox.setChecked(true);
						break;
					}
				}
			}
			if (!TextUtils.isEmpty(address.getName())) {
				holder.name.setText(address.getName());
			}
			if (!TextUtils.isEmpty(address.getHeadUrl())) {
				Glide.with(context)
						.load(address.getHeadUrl())
						.transform(new GlideCircleTransform(context))
						.placeholder(R.drawable.rc_ic_def_msg_portrait)
						.error(R.drawable.rc_ic_def_msg_portrait)
						.diskCacheStrategy(DiskCacheStrategy.ALL)
						.into(holder.img);
			} else {
				holder.img.setImageResource(R.drawable.rc_ic_def_msg_portrait);
			}

			final CheckBox checkBox = holder.checkBox;
			holder.clickArea.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					checkBox.setChecked(!checkBox.isChecked());
					boolean temp = false;
					User tempBean = null;
					for (User groupMemberBean : SelectFriendsActivity.choosed) {
						if (TextUtils.equals(groupMemberBean.getId(), address.getId())) {
							temp = true;
							tempBean = groupMemberBean;
							break;
						}
					}
					if (checkBox.isChecked()) {
						if (!temp) {
							SelectFriendsActivity.choosed.add(address);
						}
					} else {
						if (temp && tempBean != null) {
							SelectFriendsActivity.choosed.remove(tempBean);
							tempBean = null;
						}
					}
					if (updateChoose != null) {
						updateChoose.update();
					}
				}
			});
		}
		return convertView;
	}

	/**
	 * 获取拼音简拼首字母
	 *
	 * @param str
	 * @return
	 */
	private String getAlpha(String str) {
		if (str == null) {
			return "#";
		}
		if (str.trim().length() == 0) {
			return "#";
		}
		char c = str.trim().substring(0, 1).charAt(0);
		// 正则表达式，判断首字母是否是英文字母
		Pattern pattern = Pattern.compile("^[A-Za-z]+$");
		if (pattern.matcher(c + "").matches()) {
			return (c + "").toUpperCase(Locale.getDefault());
		} else {
			return "#";
		}
	}
	
	public void setWordVisible(boolean show){
		showWord = show;
	}
	
	class ViewHolder {
		TextView word;
		TextView name;
        ImageView img, img_mark;
        CheckBox checkBox;
		LinearLayout clickArea;
	}

}
